package com.inkrl.setup.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.inkrl.setup.mapper.SetUpMapper;
import com.jt.common.pojo.Address;
import com.jt.common.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class SetUpServiceImpl implements SetUpService {
    @Autowired(required = false)
    private SetUpMapper setUpMapper;

    private StringRedisTemplate template;
    private static final ObjectMapper mapper = new ObjectMapper();

    @Override
    public String queryPassword(String upwd, String token) {
        ValueOperations<String,String> opsForValue = template.opsForValue();
        if (template.hasKey(token)){
            String userJson = opsForValue.get(token);
            try {
                User user = mapper.readValue(userJson,User.class);
                User user1 = setUpMapper.selectByUandP(upwd,user.getUsername());
                if(user1!=null){
                    return "yes";
                }
                return "no";
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        return "null";
    }

    @Override
    public String updatePassword(String upwd,String token) {
        ValueOperations<String,String> opsForValue = template.opsForValue();
        String userJson = opsForValue.get(token);
        try {
            User user = mapper.readValue(userJson,User.class);
            int i = setUpMapper.updateByUandP(upwd,user.getUsername());
            if(i>0){
                return "yes";
            }
            return "no";
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public String addAddress(Address address, String token) {
        ValueOperations<String,String> opsForValue = template.opsForValue();
        String userJson = opsForValue.get(token);
        try {
            User user = mapper.readValue(userJson,User.class);
            address.setUserId(user.getPhone());
            address.setAdded(new Date());
            int i = setUpMapper.insertAddress(address);
            if (i>0){
                return "yes";
            }
            return "no";
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
